import { ComputedRef } from 'vue'

interface LoadParams {
  pageIndex: number
  pageSize: number
  [key: string]: any
}

export default function useLoadMore(
  requestFun: (...args: any) => Promise<void>,
  total: ComputedRef<number>,
  params: LoadParams = { pageIndex: 0, pageSize: 8 }
) {
  const requestParams = reactive(params)

  const loadMorePage = async () => {
    requestParams.pageIndex++
    await requestFun(requestParams)
  }

  const loadPrevPage = async () => {
    requestParams.pageIndex--
    await requestFun(requestParams)
  }

  const goToPage = async (index: number) => {
    if (requestParams.pageIndex === index) return
    requestParams.pageIndex = index
    await requestFun(requestParams)
  }

  const totalPage = computed(() => Math.ceil(total.value / requestParams.pageSize))

  const isFirstPage = computed(() => {
    return requestParams.pageIndex === 0
  })

  const isLastPage = computed(() => {
    return totalPage.value === requestParams.pageIndex + 1
  })

  const pageIndex = toRef(requestParams, 'pageIndex')

  return {
    loadMorePage,
    isLastPage,
    pageIndex,
    loadPrevPage,
    isFirstPage,
    requestParams,
    totalPage,
    goToPage
  }
}
